package com.markhsiu.test;

import java.util.concurrent.locks.ReentrantReadWriteLock;

public final class RecordsRingBuffer {
	public final static int bufferSize = 128;
	public static RecordsBuffer[] buffer = new RecordsBuffer[bufferSize];
	public static int head = 0;
	public static int tail = 0;
	private static ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
	
	public static Boolean empty() {
		return head == tail;
	}
	
	public static Boolean full() {
		return (tail + 1) % bufferSize == head;
	}
	
//	private  static Boolean put(RecordsBuffer v) {
//		lock.writeLock().lock();
//		if (full()) {
//			return false;
//		}
//		buffer[tail] = v;
//		tail = (tail + 1) % bufferSize;
//		lock.writeLock().unlock();
//		return true;
//	}
	
	public  static Block exchang(Block block) {
		lock.writeLock().lock();
		if (full()) {
			return null;
		}
		RecordsBuffer result = buffer[tail];
		if(result == null){
			result = new RecordsBuffer();
			result.block = new Block();
		}
		
		Block emptyBlock = result.block;
		emptyBlock.limit = 0;
		emptyBlock.id = 0;
		
		result.block  = block;
		tail = (tail + 1) % bufferSize;
		lock.writeLock().unlock();
		return emptyBlock;
	}
	
	public  static RecordsBuffer get() {
		lock.readLock().lock();
		if (empty()) {
			return null;
		}
		RecordsBuffer result = buffer[head];
		head = (head + 1) % bufferSize;
		lock.readLock().lock();
		return result;
	}

}